from _decimal import Decimal

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

from goods.models import SKU
from orders.serializers import OrderSettlementSerializer, SaveOrderSerializer


class OrderSettlementView(APIView):
    """订单结算视图"""
    # 身份认证
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 获取用户对象
        user = request.user

        # 从redis中查询数据,sku_id, count, selected
        redis_conn = get_redis_connection('cart')

        # 从hash中查询出本用户的所有数据
        redis_cart_dict = redis_conn.hgetall('cart_%s' % user.id)

        # 从set中查询出所有勾选数据
        redis_cart_selected = redis_conn.smembers('cart_selected_%s' % user.id)

        # 单独查询出勾选对象
        cart = {}

        for sku_id in redis_cart_selected:
            cart[int(sku_id)] = int(redis_cart_dict[sku_id])

        # cart:已经勾选的对象和他的数量
        # 查询数据库,已经勾选对象列表
        sku_id_list = cart.keys()
        sku_obj_list = SKU.objects.filter(id__in=sku_id_list)

        # 往查询出来查询集合的每个对象中添加count属性
        for sku in sku_obj_list:
            sku.count = cart[sku.id]

        # 运费
        freight = Decimal('10.00')

        # 将准备好的数据序列化返回
        serializer = OrderSettlementSerializer({'freight': freight, 'skus': sku_obj_list})
        return Response(serializer.data)


class SaveOrderView(CreateAPIView):
    """保存订单"""
    serializer_class = SaveOrderSerializer
    # 保存前需要校验身份
    permission_classes = [IsAuthenticated]

    # 提供post方法 ,其他的额放序列化器里执行
    # def post(self, request, *args, **kwargs):
        # 接受参数
        #校验参数
        #获取购物车勾选结算的数据
        # 创建订单表保存
        # 序列化返回